package com.fingard.dsp.bank.directbank.ccb12;

import com.allinpay.ets.client.StringUtil;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IContract;
import com.fingard.dsp.bank.reqrespobj.contract.*;
import com.fingard.dsp.bank.reqrespobj.contract.detail.RetAtsContractDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;


public class CCB12Contract extends CCB12Base implements IContract {

    @Override
    public RetAtsContract contract(ReqContract p_req) throws Exception {
        String contractDelay = getBankConfig().getValueAsString("contractDelay");
        if ("true".equals(contractDelay.toLowerCase())) {
            long realSleepTime = getBankConfig().getValueAsInt("contractDelayTime");
            Thread.sleep(realSleepTime * 1000);
        }
        RetAtsContract retAts = new RetAtsContract(p_req.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req.contractDetail.recAct, "contract");
            if (actItem == null) {
                throw new Exception("未找到账号" + p_req.contractDetail.recAct + "对应的商户配置信息");
            }
            String deadLine = p_req.contractDetail.deadLine;
            if (StringHelper.isNullOrEmpty(deadLine)) {
                deadLine = getBankConfig().getMapValueByKey("contractKeyMapping", "deadLine");
                if (StringHelper.isNullOrEmpty(deadLine)) {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = "缺失配置节点'deadLine'或值为空!";
                    retAts.writeRetDetail(tmpRetDetail);
                    return retAts;
                }
            }
            String singleLimit = p_req.contractDetail.singleLimit;
            if (StringHelper.isNullOrEmpty(singleLimit)) {
                if (getBankConfig().getValueAsBool("singleLimitCut")) {
                    singleLimit = getBankConfig().getMapValueByKey("singleLimitMapping", p_req.contractDetail.payBankCode);
                } else {
                    singleLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "singleLimit");
                }

                if (StringHelper.isNullOrEmpty(singleLimit)) {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = "缺失配置节点'singleLimit'或值为空!";
                    retAts.writeRetDetail(tmpRetDetail);
                    return retAts;
                }
            }
            String countLimit = p_req.contractDetail.countLimit;
            boolean fixCountLimit = getBankConfig().getValueAsBool("fixCountLimit");
            if (fixCountLimit || StringHelper.isNullOrEmpty(countLimit)) {
                countLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "countLimit");
                if (StringHelper.isNullOrEmpty(countLimit)) {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = "缺失配置节点'countLimit'或值为空!";
                    retAts.writeRetDetail(tmpRetDetail);
                    return retAts;
                }
            }
            XmlTextWriter xmlWriter = new XmlTextWriter();
            if ("01".equals(p_req.contractDetail.step)) {
                txCode = "P5381916F";
                reqSeqID = p_req.contractDetail.askNumber;
                writeCommonHeader(xmlWriter, actItem);
                xmlWriter.writeStartElement("APP_ENTITY");
                xmlWriter.writeElementString("InsPolcy_No", p_req.contractDetail.insuPolicyNum);
                xmlWriter.writeElementString("Plchd_Nm", p_req.contractDetail.payName);
                xmlWriter.writeElementString("Plchd_Crdt_TpCd", convertCertTypeToBank(p_req.contractDetail.certType));
                xmlWriter.writeElementString("Plchd_Crdt_No", p_req.contractDetail.certNum);
                xmlWriter.writeElementString("Plchd_PyF_AccNo", p_req.contractDetail.payAct);
                xmlWriter.writeElementString("Mnplt_Tp_Ind", "1");


            } else if ("02".equals(p_req.contractDetail.step)) {
                txCode = "P5381916G";
                reqSeqID = p_req.reqHeader.transSeqID;
                writeCommonHeader(xmlWriter, actItem);
                xmlWriter.writeStartElement("APP_ENTITY");
                xmlWriter.writeElementString("InsPolcy_No", p_req.contractDetail.insuPolicyNum);
                xmlWriter.writeElementString("Plchd_Nm", p_req.contractDetail.payName);
                xmlWriter.writeElementString("Plchd_Crdt_TpCd", convertCertTypeToBank(p_req.contractDetail.certType));
                xmlWriter.writeElementString("Plchd_Crdt_No", p_req.contractDetail.certNum);
                xmlWriter.writeElementString("Plchd_PyF_AccNo", p_req.contractDetail.payAct);
                xmlWriter.writeElementString("SMS_Vld_CD", p_req.contractDetail.smsCode);
                xmlWriter.writeElementString("Orig_TxnSrlNo", p_req.contractDetail.token);
                xmlWriter.writeElementString("Cvr_ID", p_req.contractDetail.insureID, true);
                xmlWriter.writeElementString("Cvr_Nm", p_req.contractDetail.insureName, true);
                if (singleLimit.indexOf(".") == -1) {
                    singleLimit = singleLimit + ".00";
                }
                xmlWriter.writeElementString("Per_Amt_UpLm_Val", singleLimit);

                xmlWriter.writeElementString("InsPrem_PyF_Prd_Num", countLimit);
                xmlWriter.writeElementString("PyF_CODt", deadLine);
                String amt = p_req.contractDetail.noteMoney;
                if (amt.indexOf(".") == -1) {
                    amt = amt + ".00";
                }
                xmlWriter.writeElementString("Tot_InsPrem_Amt", amt);
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未能识别的step：" + p_req.contractDetail.step;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            xmlWriter.writeEndDocument();
            String tmpStrRet = sendToBank(xmlWriter.toXmlString());
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet, tmpSbMsg);
            if (tmpBkReader != null) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = tmpBkReader.getFirstText("/TX/TX_HEADER/SYS_RESP_DESC");
                String status = tmpBkReader.getFirstText("/TX/TX_HEADER/SYS_TX_STATUS");
                String respCode = tmpBkReader.getFirstText("/TX/TX_HEADER/SYS_RESP_CODE");
                if ("01".equals(p_req.contractDetail.step)) {
                    String signno = tmpBkReader.getFirstText("/TX/TX_BODY/ENTITY/APP_ENTITY/InsPolcy_No");
                    if (!"00".equals(status)) {
                        tmpRetDetail.respCode = "-1";
                    }
                    if ("000000000000".equals(respCode) && !StringUtil.isEmpty(signno)) {
                        tmpRetDetail.authCode = signno;
                    }
                    tmpRetDetail.token = tmpBkReader.getFirstText("/TX/TX_BODY/ENTITY/COM_ENTITY/SvPt_Jrnl_No");
                    tmpRetDetail.signConfirmType = "2";
                } else {
                    if (!"00".equals(status)) {
                        tmpRetDetail.respCode = "-1";
                    }
                    if ("000000000000".equals(respCode)) {
                        tmpRetDetail.signState = ContractState.SUCCESS;
                    }else if ("YBLA0381213U".equals(respCode)) {
                        tmpRetDetail.signState = ContractState.SIGNING;
                    } else {
                        tmpRetDetail.signState = ContractState.FAIL;
                    }
                }
                tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", respCode);
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpSbMsg.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsContract upContract(ReqContract p_req) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_req.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req.contractDetail.recAct, "contract");
            if (actItem == null) {
                throw new Exception("未找到账号" + p_req.contractDetail.recAct + "对应的商户配置信息");
            }
            XmlTextWriter xmlWriter = new XmlTextWriter();
            if ("01".equals(p_req.contractDetail.step)) {
                txCode = "P5381916F";
                reqSeqID = p_req.contractDetail.askNumber;
                writeCommonHeader(xmlWriter, actItem);
                xmlWriter.writeStartElement("APP_ENTITY");
                xmlWriter.writeElementString("InsPolcy_No", p_req.contractDetail.insuPolicyNum);
                xmlWriter.writeElementString("Plchd_Nm", p_req.contractDetail.payName);
                xmlWriter.writeElementString("Plchd_Crdt_TpCd", convertCertTypeToBank(p_req.contractDetail.certType));
                xmlWriter.writeElementString("Plchd_Crdt_No", p_req.contractDetail.certNum);
                xmlWriter.writeElementString("Plchd_PyF_AccNo", p_req.contractDetail.payAct);
                xmlWriter.writeElementString("Mnplt_Tp_Ind", "2");
            } else if ("02".equals(p_req.contractDetail.step)) {
                txCode = "P5381916H";
                reqSeqID = p_req.reqHeader.transSeqID;
                writeCommonHeader(xmlWriter, actItem);
                xmlWriter.writeStartElement("APP_ENTITY");
                xmlWriter.writeElementString("InsPolcy_No", p_req.contractDetail.insuPolicyNum);
                xmlWriter.writeElementString("Plchd_Nm", p_req.contractDetail.payName);
                xmlWriter.writeElementString("Plchd_Crdt_TpCd", convertCertTypeToBank(p_req.contractDetail.certType));
                xmlWriter.writeElementString("Plchd_Crdt_No", p_req.contractDetail.certNum);
                xmlWriter.writeElementString("Plchd_PyF_AccNo", p_req.contractDetail.payAct);
                xmlWriter.writeElementString("SMS_Vld_CD", p_req.contractDetail.smsCode);
                xmlWriter.writeElementString("Orig_TxnSrlNo", p_req.contractDetail.token);
                xmlWriter.writeElementString("Cvr_ID", p_req.contractDetail.insureID, true);
                String singleLimit = p_req.contractDetail.singleLimit;
                if(StringHelper.hasAnyChar(singleLimit)){
                    if (singleLimit.indexOf(".") == -1) {
                        singleLimit = singleLimit + ".00";
                    }
                    xmlWriter.writeElementString("Per_Amt_UpLm_Val", singleLimit);
                }
                String countLimit = p_req.contractDetail.countLimit;
                if(StringHelper.hasAnyChar(countLimit)){
                    xmlWriter.writeElementString("InsPrem_PyF_Prd_Num", countLimit);
                }

                String deadLine = p_req.contractDetail.deadLine;
                if(StringHelper.hasAnyChar(deadLine)){
                    xmlWriter.writeElementString("PyF_CODt", deadLine);
                }
                String amt = p_req.contractDetail.noteMoney;
                if(StringHelper.hasAnyChar(amt)){
                    if (amt.indexOf(".") == -1) {
                        amt = amt + ".00";
                    }
                    xmlWriter.writeElementString("Tot_InsPrem_Amt", amt);
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未能识别的step：" + p_req.contractDetail.step;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            xmlWriter.writeEndDocument();
            String tmpStrRet = sendToBank(xmlWriter.toXmlString());
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet, tmpSbMsg);
            if (tmpBkReader != null) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = tmpBkReader.getFirstText("/TX/TX_HEADER/SYS_RESP_DESC");
                String status = tmpBkReader.getFirstText("/TX/TX_HEADER/SYS_TX_STATUS");
                String respCode = tmpBkReader.getFirstText("/TX/TX_HEADER/SYS_RESP_CODE");
                if ("01".equals(p_req.contractDetail.step)) {
                    String signno = tmpBkReader.getFirstText("/TX/TX_BODY/ENTITY/APP_ENTITY/InsPolcy_No");
                    if (!"00".equals(status)) {
                        tmpRetDetail.respCode = "-1";
                    }
                    if ("000000000000".equals(respCode) && !StringUtil.isEmpty(signno)) {
                        tmpRetDetail.authCode = signno;
                    }
                    tmpRetDetail.token = tmpBkReader.getFirstText("/TX/TX_BODY/ENTITY/COM_ENTITY/SvPt_Jrnl_No");
                    tmpRetDetail.step = "01";
                } else {
                    if (!"00".equals(status)) {
                        tmpRetDetail.respCode = "-1";
                    }
                    if ("000000000000".equals(respCode)) {
                        tmpRetDetail.signState = ContractState.SUCCESS;
                    }else if ("YBLA0381213U".equals(respCode)) {
                        tmpRetDetail.signState = ContractState.SIGNING;
                    } else {
                        tmpRetDetail.signState = ContractState.FAIL;
                    }
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpSbMsg.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsContract qryContract(ReqContract p_reqQry) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_reqQry.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_reqQry.contractDetail.askNumber;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_reqQry.contractDetail.recAct, "contract");
            if (actItem == null) {
                if (actItem == null) {
                    throw new Exception("未找到账号" + p_reqQry.contractDetail.recAct + "对应的商户配置信息");
                }
            }
            txCode = "P5381916E";
            reqSeqID = p_reqQry.reqHeader.transSeqID;
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, actItem);
            xmlWriter.writeStartElement("APP_ENTITY");
            xmlWriter.writeElementString("InsPolcy_No", p_reqQry.contractDetail.insuPolicyNum);
            xmlWriter.writeElementString("Cvr_ID", p_reqQry.contractDetail.insureID, true);
            xmlWriter.writeElementString("Plchd_Crdt_TpCd", convertCertTypeToBank(p_reqQry.contractDetail.certType));
            xmlWriter.writeElementString("Plchd_Nm", p_reqQry.contractDetail.payName);
            xmlWriter.writeElementString("Plchd_Crdt_No", p_reqQry.contractDetail.certNum);
            ;
            xmlWriter.writeEndDocument();
            String tmpStrRet = sendToBank(xmlWriter.toXmlString());
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet, tmpSbMsg);
            if (tmpBkReader != null) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = tmpBkReader.getFirstText("/TX/TX_HEADER/SYS_RESP_DESC");
                String status = tmpBkReader.getFirstText("/TX/TX_HEADER/SYS_TX_STATUS");
                String respCode = tmpBkReader.getFirstText("/TX/TX_HEADER/SYS_RESP_CODE");
                String signno = tmpBkReader.getFirstText("/TX/TX_BODY/ENTITY/APP_ENTITY/InsPolcy_No");
                String signStatus = tmpBkReader.getFirstText("/TX/TX_BODY/ENTITY/APP_ENTITY/Ahn_Ind");
                if (!"00".equals(status)) {
                    tmpRetDetail.respCode = "-1";
                }
                if ("1".equals(signStatus)) {
                    tmpRetDetail.signState = ContractState.SUCCESS;
                    tmpRetDetail.authCode = signno;
                } else if ("0".equals(signStatus)) {
                    tmpRetDetail.signState = ContractState.UNSIGNED;
                }
                tmpRetDetail.signConfirmType = "2";
                tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", respCode);
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpSbMsg.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsQryBatContract qryBatContract(ReqQryBatContract p_reqQry) throws Exception {
        return null;
    }
}
